<?php

namespace app\beautiful\controller\admin;

use app\beautiful\logic\LogsLogic;

use app\beautiful\model\CouponModel;

use app\beautiful\model\LevelModel;

use app\beautiful\model\member\MemberBalanceModel;

use app\beautiful\model\member\MemberCouponModel;

use app\beautiful\model\member\MemberIntegralModel;

use app\beautiful\model\member\MemberLockModel;
use app\beautiful\model\member\MemberModel;

use app\beautiful\model\PartnerModel;
use app\beautiful\model\setting\LevelSettingModel;
use app\beautiful\model\setting\SettingBalanceModel;

use app\beautiful\model\StaffMemberModel;

use app\beautiful\model\StaffModel;

use app\BaseController;

use app\common\logic\DataLogic;

use app\beautiful\logic\MemberWalletLogic;

use app\beautiful\model\member\MemberOnceCardModel;

use app\stores\model\member\MemberLevelModel;
use think\facade\Db;


/*多店版代码*/
class Member extends BaseController{

    protected $name='会员';



    public function index()

    {
        $member_id=$this->request->param('member_id/d',0);

        $nick_name=$this->request->param('nick_name');

        $mobile=$this->request->param('mobile');

        $level_id=$this->request->param('level_id/d',-99);

        $birthday_type=$this->request->param('birthday_type/d',1);

        $in_white_list=$this->request->param('in_white_list','');

        $is_lock=$this->request->param('is_lock','');

        $where=[

            ['is_delete','=',0],

        ];
        $select_setting = LevelSettingModel::where(['shop_id'=>$this->request->shopId,'is_selected'=>1])->find();
        if(empty($select_setting)) $select_setting->type = 0;
        $level=LevelModel::where([['shop_id','=',$this->request->shopId],['is_delete','=',0],['type','=',$select_setting->type]])->field('level_id,name')->select()->toArray();
        //在用户门店等级表存在的用户
        $member_ids = shopMembers($this->request->shopId);
        $data['list']=[];
        $data['level']=$level;
        if (empty($member_ids)) return $this->success($data);
        if($member_ids) $where[]=['member_id','In',$member_ids];

        if($member_id>0)  $where[]=['member_id','=',$member_id];

        if(!empty($nick_name))  $where[]=['nick_name','=',$nick_name];

        if(!empty($mobile))  $where[]=['mobile','=',$mobile];


        if($level_id!=-99)  $where[]=['level_id','=',$level_id];



        if(in_array($birthday_type,[2,3])){

            if($birthday_type==2)   $month=date("m");

            if($birthday_type==3)   $month=date("m",strtotime("+1 month"));

            $where[]=['birthday_month','=',$month];

        }




        $memberModel=new MemberModel();
        $shop_id = $this->request->shopId;
        $memberModel = $memberModel::with(['partner'=>function($query) use ($shop_id){
            $query->where(['shop_id'=>$shop_id]);
        }]);
        if($in_white_list!==''){
            $member_id_arr=$memberModel->where("JSON_CONTAINS(white_list_shop,JSON_OBJECT('shop_id',".$this->request->shopId.")) and JSON_CONTAINS(white_list_shop,JSON_OBJECT('in_white_list',1))")->column('member_id');
            if($in_white_list>0){
                $where[]=['member_id','in',implode(',',$member_id_arr)];
            }else{
                $where[]=['member_id','not in',implode(',',$member_id_arr)];
            }

        }

        if($is_lock!==''){
            //在用户门店锁客用户
            $l_member_ids = shopMemberlock($this->request->shopId);
            if($is_lock>0){
                $where[] =['member_id','In',$l_member_ids];
            }else{
                $where[] =['member_id','not in',$l_member_ids];
            }
        }

        $memberModel=$memberModel->json(['white_list_shop'],true);

        $order=['add_time'=>'desc'];

        $append=['birthday'];

        $field='member_id,nick_name,face,mobile,vip_start_time,vip_end_time,birthday_year,birthday_month,birthday_day';

        $data=DataLogic::getDataList($memberModel,$where,$order,$field,$this->request->limit,$this->request->page,$append);

   

        //处理数据

        $lists=$data['list'];

        if(empty(!$lists)){                 

            $memberIds = $balances = $integrals = [];

            foreach($lists as $key=>$val){
                $memberIds[$val['member_id']] = $val['member_id'];

            }

            if(!empty($memberIds)){

               $MemberBalanceModel = new MemberBalanceModel();

               $balances =  $MemberBalanceModel->getBalanceSumByMemberId($memberIds,0,$this->request->shopId);

               $MemberIntegralModel = new MemberIntegralModel();

               $integrals = $MemberIntegralModel->getIntegralSumByMemberId($memberIds);

            }

            $key_start = $this->request->limit * ($this->request->page - 1);

            $key_end = $data['total'];

            $member_level_model = new MemberLevelModel();
            $level_model = new LevelModel();
            foreach ($lists as $k => $list){
                $key = false;
                if($list['white_list_shop']){
                    $shop_id_arr = array_column($list['white_list_shop'], 'shop_id');

                    $key = array_search($this->request->shopId, $shop_id_arr);
                }

                $lists[$k]['white_list_info'] =[
                    'in_white_list' => ($key!==false)?$list['white_list_shop'][$key]['in_white_list']:0,
                    'real_name' => ($key!==false)?$list['white_list_shop'][$key]['real_name']:'',
                    'white_list_time' => ($key!==false)?$list['white_list_shop'][$key]['start_time'].'至'.$list['white_list_shop'][$key]['end_time']:'',
                ];

                $lists[$k]['show_member_id']= $key_end - ($key_start + $k);

                $lists[$k]['balance']=$balances[$list['member_id']] ?? 0;

                $lists[$k]['integral']=$integrals[$list['member_id']] ?? 0;

                $lists[$k]['member_id']=sprintf("%08d", $list['member_id']);
                $lists[$k]['memberId']=$list['member_id'];
                $l_s=[];
                $l_s['shop_id']=$this->request->shopId;
                $l_s['member_id']=$list['member_id'];
                $member_lock=MemberLockModel::where($l_s)->find();
                $lists[$k]['is_lock']=0;
                if(!empty($member_lock)){
                    $lists[$k]['is_lock']=1;
                }
                $member_level = $member_level_model->getById(['shop_id'=>$this->request->shopId,'member_id'=>$list['member_id'],'is_delete'=>0]);
                if($member_level){
                    $level_info = $level_model->getById(['shop_id'=>$this->request->shopId,'level_id'=>$member_level['level_id'],'is_delete'=>0]);
                }
                $lists[$k]['level_name']=(isset($level_info) && $level_info)?$level_info['name']:null;
                //判断会员是否是股东
                $lists[$k]['partner_name']=$list['partner']?$list['partner']['name']:null;
                unset($lists[$k]['partner']);
            }

        }

        $data['list']=$lists;

        $data['level']=$level;

        return $this->success($data);

    }



    public function show()

    {

        $member_id=$this->request->param('member_id/d',0);

        if(null === $member = MemberModel::find($member_id)) return $this->error($this->name.'不存在');

        if($member->is_delete != 0)  return $this->error($this->name.'不存在');

        if($member->shop_id != $this->request->shopId)   return $this->error($this->name.'不存在');



        $balance = MemberBalanceModel::where([

                ['shop_id','=',$this->request->shopId],

                ['member_id','=',$member_id],

                ['valid_bg_time','<=',$this->request->time()]

            ])->sum('remain_balance') ?? 0;



        $integral = MemberIntegralModel::where([

                ['shop_id','=',$this->request->shopId],

                ['member_id','=',$member_id],

                ['expire_time','>',$this->request->time()]

            ])->sum('remain_integral') ?? 0;



        $detail=[

            'balance'=>$balance,

            'integral'=>$integral,

        ];

        return $this->success(['detail'=>$detail]);

    }



    public function save()

    {

        $nick_name=$this->request->param('nick_name');

        $mobile=$this->request->param('mobile');

        $birthday=$this->request->param('birthday');

        $level_id=$this->request->param('level_id/d',0);

        if(empty($nick_name)){

            return $this->error('请填写昵称');

        }

        if(empty($mobile) || !is_mobile($mobile)){

            return $this->error('请填写正确的手机号');

        }

        if(empty($birthday)){

            return $this->error('请选择生日');

        }

        if(false === $birthday_unix=strtotime($birthday)){

            return $this->error('请选择正确的生日');

        }

        $birthday_arr=explode('-',$birthday);

        $birthday_year=$birthday_arr[0];

        $birthday_month=$birthday_arr[1];

        $birthday_day=$birthday_arr[2];



        if(null !== MemberModel::where([

                ['shop_id','=',$this->request->shopId],

                ['is_delete','=',0],

                ['mobile','=',$mobile]

            ])->find()){

            return $this->error('改手机号已注册');

        }



        $member= new MemberModel();

        $member->shop_id=$this->request->shopId;

        $member->nick_name=$nick_name;

        $member->mobile=$mobile;

        $member->birthday_year=$birthday_year;

        $member->birthday_month=$birthday_month;

        $member->birthday_day=$birthday_day;

        $member->level_id=$level_id;
        
        $member->save();

        $return=[

            'member'=>[

                'member_id'=>$member->member_id,

                'nick_name'=>$member->nick_name,

                'mobile'=>$member->mobile,

            ]

        ];

        

        return $this->success($return);



    }



    public function export()

    {



        $nick_name=$this->request->param('nick_name');

        $mobile=$this->request->param('mobile');

        $level_id=$this->request->param('level_id/d',-99);

        $birthday_type=$this->request->param('birthday_type/d',1);

        $where=[

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

        ];

        if(!empty($nick_name))  $where[]=['nick_name','=',$nick_name];



        if(!empty($mobile))  $where[]=['mobile','=',$mobile];



        if($level_id!=-99)  $where[]=['level_id','=',$level_id];



        if(in_array($birthday_type,[2,3])){

            if($birthday_type==2)   $month=date("m");

            if($birthday_type==3)   $month=date("m",strtotime("+1 month"));

            $where[]=['birthday_month','=',$month];

        }



        $memberModel=new MemberModel();

        $memberModel=$memberModel->with(['level'=>function($query){

            $query->field('level_id,name');

        }]);

        $order=['add_time'=>'desc'];

        $append=['birthday'];

        $field='member_id,nick_name,face,mobile,birthday_year,birthday_month,birthday_day';

        $data= $list=$memberModel->where($where)

            ->field($field)->order($order)

            ->limit(200)->page($this->request->page)

            ->select()

            ->append($append)

            ->toArray();



        //处理数据

        $csvArr=[];

        if(empty(!$data)){

            $memberIds = $balances = $integrals = [];

            foreach($data as $val){

                $memberIds[$val['member_id']] = $val['member_id'];

            }

            if(!empty($memberIds)){

                $MemberBalanceModel = new MemberBalanceModel();

                $balances =  $MemberBalanceModel->getBalanceSumByMemberId($memberIds);

                $MemberIntegralModel = new MemberIntegralModel();

                $integrals = $MemberIntegralModel->getIntegralSumByMemberId($memberIds);

            }

            foreach ($data as $k => $list){

                $csvArr[]=[

                    $list['nick_name'],

                    $list['mobile'],

                    isset($list['level']) ? $list['level']['name'] : '普通会员',

                    $balances[$list['member_id']] ?? 0,

                    $integrals[$list['member_id']] ?? 0

                ];

            }

        }



        $this->download_send_headers("data_export_" . date("Y-m-d") . ".csv");

        $head=array('会员昵称','会员手机号','会员等级','会员余额','会员积分');

        echo $this->array2csv($csvArr,$head);

        unset($csvArr);

        die();



    }



    protected  function array2csv(array &$array,$head)



    {



        if (count($array) == 0) {



            return null;



        }



        ob_start();



        $df = fopen("php://output", 'w');



        if(!$head){



            $head=array_keys(reset($array));



        }



        fputcsv($df,$head);



        foreach ($array as $row) {



            fputcsv($df, $row);



        }



        fclose($df);



        return ob_get_clean();



    }



    protected function download_send_headers($filename)

    {

        // disable caching



        $now = gmdate("D, d M Y H:i:s");



        header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");



        header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");



        header("Last-Modified: {$now} GMT");



        // force download



        header("Content-Type: application/force-download");



        header("Content-Type: application/octet-stream");



        header("Content-Type: application/download");



        // disposition / encoding on response body



        header("Content-Disposition: attachment;filename={$filename}");



        header("Content-Transfer-Encoding: binary");

    }



    public function saveNickName()

    {

        $member_id=$this->request->param('member_id/d',0);

        $nick_name=$this->request->param('nick_name');

        $mobile=$this->request->param('mobile');


        if(null === $member = MemberModel::find($member_id)) return $this->error($this->name.'不存在');

        if($member->is_delete != 0)  return $this->error($this->name.'不存在');

        //if($member->shop_id != $this->request->shopId)   return $this->error($this->name.'不存在');



        if(empty($nick_name)) return $this->error('请输入会员昵称');
        if(empty($mobile)) return $this->error('请输入手机号');

        $member->nick_name=$nick_name;
        $member->mobile=$mobile;

        $member->save();

        return $this->success('修改成功');

    }

    public function showWhiteList(){
        $member_id = $this->request->param('member_id/d',0);

        if(null === $member = MemberModel::where(['member_id'=>$member_id])->json(['white_list_shop'],true)->find()) return $this->error($this->name.'不存在');

        if($member->is_delete != 0)  return $this->error($this->name.'不存在');

        if($member->shop_id != $this->request->shopId)   return $this->error($this->name.'不存在');

        $white_list_shop = $member->white_list_shop;//白名单门店

        $detail = '';

        if($white_list_shop){
            $shop_id_arr = array_column($white_list_shop, 'shop_id');

            $key = array_search($this->request->shopId, $shop_id_arr);

            $detail=($key!==false)?$white_list_shop[$key]:'';
        }

        return $this->success(['detail'=>$detail]);
    }

    public function saveWhiteList(){
        $member_id = $this->request->param('member_id/d',0);
        $in_white_list  =$this->request->param('in_white_list/d',0);//是否加入白名单1是0否
        $real_name  =$this->request->param('real_name','');
        $start_time  =$this->request->param('start_time','');
        $end_time  =$this->request->param('end_time','');

        if($in_white_list>0 && ($start_time=='' || $end_time==''))  return $this->error('参数有误');

        $white_list = [
            'shop_id'=>$this->request->shopId,
            'in_white_list'=>$in_white_list,
            'real_name'=>$real_name,
            'start_time'=>$start_time,
            'end_time'=>$end_time
        ];
        if(null === $member = MemberModel::where(['member_id'=>$member_id])->json(['white_list_shop'],true)->find()) return $this->error($this->name.'不存在');

        if($member->is_delete != 0)  return $this->error($this->name.'不存在');

        if($member->shop_id != $this->request->shopId)   return $this->error($this->name.'不存在');

        $white_list_shop=$member->white_list_shop;

        if($white_list_shop){

            $shop_id_arr = array_column($white_list_shop, 'shop_id');

            $key = array_search($this->request->shopId, $shop_id_arr);

            if($key!==false){
                $white_list_shop[$key] = $white_list;
            }else{
                $white_list_shop[] = $white_list;
            }

        }else{
            $white_list_shop[] = $white_list;
        }

        MemberModel::where([['member_id','=',$member_id]])->json(['white_list_shop'])->update(['white_list_shop'=>$white_list_shop]);


        return $this->success('修改成功');
    }




    /****************************************************** --start--会员详情--start--*********************************************************************/



    public function detail()

    {

        $member_id=$this->request->param('member_id/d',0);

        if(null === $member = MemberModel::find($member_id)){

            return $this->error($this->name.'不存在');

        }

        if($member->is_delete != 0){

            return $this->error($this->name.'不存在');

        }

//        if($member->shop_id != $this->request->shopId){
//
//            return $this->error($this->name.'不存在');
//
//        }

        $member->append(['birthday']);



        $once_card_num=MemberOnceCardModel::where([

                ['shop_id','=',$this->request->shopId],

                ['member_id','=',$member_id],

            ])->count() ?? 0;



        $balance = MemberBalanceModel::where([

                ['shop_id','=',$this->request->shopId],

                ['member_id','=',$member_id],

            ])->sum('remain_balance') ?? 0;



        $use_balance = MemberBalanceModel::where([

            ['shop_id','=',$this->request->shopId],

            ['member_id','=',$member_id],

            ['valid_bg_time','<=',$this->request->time()]

        ])->sum('remain_balance') ?? 0;



        $frozen_balance = MemberBalanceModel::where([

                ['shop_id','=',$this->request->shopId],

                ['member_id','=',$member_id],

                ['valid_bg_time','>',$this->request->time()]

            ])->sum('remain_balance') ?? 0;



        $integral = MemberIntegralModel::where([

            ['shop_id','=',$this->request->shopId],

            ['member_id','=',$member_id],

            ['expire_time','>',$this->request->time()]

        ])->sum('remain_integral') ?? 0;



        $coupon_count = MemberCouponModel::where([

            ['shop_id','=',$this->request->shopId],

            ['member_id','=',$member_id],

        ])->count() ?? 0;

        //是否是股东
        $partner = PartnerModel::where( [

            ['shop_id','=',$this->request->shopId],

            ['member_id','=',$member_id],

            ['status','=',1],

            ['is_delete','=',0],

        ])->find();

        $detail=[

            'nick_name'=>$member->nick_name,

            'level_name'=>$member->level ? $member->level->name : '普通会员',

            'mobile'=>$member->mobile,

            'face'=>$member->face,

//            'adviser'=>$member->adviser ? $member->adviser->staff->name : '暂无',

//            'staff_id'=>$member->adviser ? $member->adviser->staff->staff_id : 0,

            'once_card_num'=>$once_card_num,

            'balance'=>$balance,

            'use_balance'=>$use_balance,

            'frozen_balance'=>$frozen_balance,

            'integral'=>$integral,

            'coupon_count'=>$coupon_count,

            'partner_type'=>$partner?$partner->type:0,

        ];

        return $this->success(['detail'=>$detail]);

    }





    public function assignAdviser()

    {

        $member_id=$this->request->param('member_id/d',0);

        if(null === $member = MemberModel::find($member_id)) return $this->error($this->name.'不存在');

        if($member->is_delete != 0)  return $this->error($this->name.'不存在');

        if($member->shop_id != $this->request->shopId)   return $this->error($this->name.'不存在');



        $staff_id = $this->request->param('staff_id/d',0);

        if(null === $staff = StaffModel::find($staff_id)) return $this->error('顾问不存在');

        if($staff->is_delete != 0)  return $this->error('顾问不存在');

        if($staff->shop_id != $this->request->shopId)   return $this->error('顾问不存在');

        if($staff->adviser_jurisdiction!=1) return $this->error('顾问不存在');

        if($staff->status != 1) return $this->error('顾问已离职');



        if(null !== $staffMember = StaffMemberModel::where([

                ['shop_id','=',$this->request->shopId],

                ['member_id','=',$member_id],

            ])->find()){

            if($staffMember->staff_id == $staff_id)   return $this->error('这个顾问本来就是这个会员的顾问');

        }else{

            $staffMember = new StaffMemberModel();

            $staffMember->shop_id = $this->request->shopId;

            $staffMember->member_id = $member_id;

        }

        $staffMember->staff_id = $staff_id;

        $staffMember->save();

        return $this->success('操作成功');



    }



    public function balanceRecharge()

    {

        $member_id=$this->request->param('member_id/d',0);

        if(null === $member = MemberModel::find($member_id)) return $this->error($this->name.'不存在');

        if($member->is_delete != 0)  return $this->error($this->name.'不存在');

        if($member->shop_id != $this->request->shopId)   return $this->error($this->name.'不存在');



        $balance= $this->request->param('balance/f',0);

        $give_balance =$this->request->param('give_balance/f',0);

        if($balance <=0 ) return $this->error('请填写充值金额，且金额不能小于等于0');

        if($give_balance < 0) return $this->error('请填写赠送金额，金额不能小于0');

        $remarks= $this->request->param('remarks');

        $balance_setting=SettingBalanceModel::where([['shop_id','=',$this->request->shopId]])->find();

        $frozen_days=$balance_setting->is_frozen_give_money ==1 ? $balance_setting->frozen_days : 0;



        Db::startTrans();

        try{

            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member_id);

            $res = $MemberWalletLogic->addBalance($balance, $give_balance, 3,$remarks, $this->request->accountId);

            if($res == false){

                Db::rollback();

                return $this->error($MemberWalletLogic->getError());

            }

            Db::commit();

            return $this->success('操作成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }



    public function balanceDeduction()

    {

        $member_id=$this->request->param('member_id/d',0);

        if(null === $member = MemberModel::find($member_id)) return $this->error($this->name.'不存在');

        if($member->is_delete != 0)  return $this->error($this->name.'不存在');

        if($member->shop_id != $this->request->shopId)   return $this->error($this->name.'不存在');



        $balance= $this->request->param('balance/f',0);

        $original_deduction =$this->request->param('original_deduction/f',0);

        if($balance <=0 ) return $this->error('请填写扣除金额，且金额不能小于等于0');

        if($original_deduction <= 0) return $this->error('请填写原本扣除金额，金额不能小于等于0');

        if($original_deduction < $balance) return $this->error('原本扣除的金额不能小于实际扣除的金额');



        $remarks=$this->request->param('remarks');



        Db::startTrans();

        try{

            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member_id);

            $res = $MemberWalletLogic->useBalance($balance, $original_deduction, 7, $remarks, $this->request->accountId);

            if($res == false){

                Db::rollback();

                return $this->error($MemberWalletLogic->getError());

            }

            Db::commit();

            return $this->success('操作成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }



    }



    public function integralRecharge()

    {

        $member_id=$this->request->param('member_id/d',0);

        if(null === $member = MemberModel::find($member_id)) return $this->error($this->name.'不存在');

        if($member->is_delete != 0)  return $this->error($this->name.'不存在');

        if($member->shop_id != $this->request->shopId)   return $this->error($this->name.'不存在');



        $integral= $this->request->param('integral/d',0);

        if($integral <=0 ) return $this->error('请填写充值积分，且积分不能小于等于0');



       



        Db::startTrans();

        try{

            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId,$member_id);

            $res = $MemberWalletLogic->addIntegal($integral, 2, '', $this->request->accountId);

            if(!$res){

                Db::rollback();

                return $this->error($MemberWalletLogic->getError());

            }

            Db::commit();

            return $this->success('操作成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }



    public function integralDeduction()

    {

        $member_id=$this->request->param('member_id/d',0);

        if(null === $member = MemberModel::find($member_id)) return $this->error($this->name.'不存在');

        if($member->is_delete != 0)  return $this->error($this->name.'不存在');

        if($member->shop_id != $this->request->shopId)   return $this->error($this->name.'不存在');



        $integral= $this->request->param('integral/d',0);

        if($integral <=0 ) return $this->error('请填写积分，且积分不能小于等于0');



        $remarks=$this->request->param('remarks');





        Db::startTrans();

        try{

            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId,$member_id);

            $res = $MemberWalletLogic->useIntegral($integral, 5,$remarks, $this->request->accountId);

            if(!$res){

                Db::rollback();

                return $this->error($MemberWalletLogic->getError());

            }

            Db::commit();

            return $this->success('操作成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }



    public function sendCoupon()

    {

        $member_id=$this->request->param('member_id/d',0);

        if(null === $member = MemberModel::find($member_id)) return $this->error($this->name.'不存在');

        if($member->is_delete != 0)  return $this->error($this->name.'不存在');

        if($member->shop_id != $this->request->shopId)   return $this->error($this->name.'不存在');



        $coupon_ids = $this->request->param('coupon_ids/a',[]);

        if(empty($coupon_ids)) return $this->error('请选择优惠券');

        $coupon_data=CouponModel::where([

            ['coupon_id','in',$coupon_ids],

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

            ['status','=',1],

            ['end_time','>=',date("Y-m-d",$this->request->time())]

        ])->field('coupon_id,name,valid_bg_time,valid_end_time,coupon_money,money_limit,add_time')

            ->select()->toArray();

        if(empty($coupon_data)) return $this->error('请选择优惠券');







        foreach ($coupon_data as $k => $coupon){

            $member_coupon_model = new MemberCouponModel();

            $member_coupon_data=[

                'shop_id'=>$this->request->shopId,

                'member_id'=>$member_id,

                'type_id'=>2,

                'coupon_id'=>$coupon['coupon_id'],

                'name'=>$coupon['name'],

                'coupon_money'=>$coupon['coupon_money'],

                'money_limit'=>$coupon['money_limit'],

                'valid_bg_time'=>$coupon['valid_bg_time'],

                'valid_end_time'=>$coupon['valid_end_time'],

            ];

            $member_coupon_model->save($member_coupon_data);



            LogsLogic::coupon($this->request->shopId,$member_id,1,3,$member_coupon_model->member_coupon_id,'',$this->request->accountId);

        }



        return $this->success('送券成功');

    }



    /****************************************************** --end--会员详情--end--*********************************************************************/





    /****************************************************** --start--会员详情优惠券--start--*********************************************************************/



    public function writeOffCoupon()

    {

        $member_id=$this->request->param('member_id/d',0);

        if(null === $member = MemberModel::find($member_id)) return $this->error($this->name.'不存在');

        if($member->is_delete != 0)  return $this->error($this->name.'不存在');

        if($member->shop_id != $this->request->shopId)   return $this->error($this->name.'不存在');



        $member_coupon_id =$this->request->param('member_coupon_id/d',0);

        if(null === $memberCoupon = MemberCouponModel::find($member_coupon_id)) return $this->error('优惠券不存在');

        if($memberCoupon->shop_id != $this->request->shopId) return $this->error('优惠券不存在');

        if($memberCoupon->member_id != $member_id) return $this->error('优惠券不存在');

        if($memberCoupon->status != 0) return $this->error('该优惠券已使用过了');

        if($memberCoupon->valid_end_time <date("Y-m-d")) return $this->error('该优惠券已过期');



        $memberCoupon->status=1;

        $memberCoupon->save();



        LogsLogic::coupon($this->request->shopId,$member_id,-1,7,$member_coupon_id,'',$this->request->accountId);

        return $this->success('核销成功');

    }



    /****************************************************** --end--会员详情优惠券--end--*********************************************************************/

    /*根据id获取用户*/
    public function getMember(){
        $member_num = $this->request->param('member_num');

        $member_model = new MemberModel();
        $member = $member_model->getById(['member_num'=>$member_num,'is_delete'=>0]);

        if(null === $member) return $this->error($this->name.'不存在');

//        $level = verifyMemberLevel($this->request->shopId,$member->member_id);
//
//        if(!$level)   return $this->error($this->name.'不存在');
        if($member->status != 1)  return $this->error($this->name.'已禁用');

        $detail = [
            'member_id'=>$member->member_id,
            'face'=>$member->face,
            'nick_name'=>$member->nick_name,
            'mobile'=>$member->mobile
        ];

        $return['detail']=$detail;

        return $this->success($return);
    }

}

